﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows;
using Microsoft.Lync.Model;
using Microsoft.Lync.Model.Group;
using System.Diagnostics;
using System;
using System.Collections.Generic;
using System.Data.SQLite;

namespace SkypeSync
{

    /// <summary>
    /// Interaction logic for Contacts.xaml
    /// </summary>
    public partial class SSContacts : Window
    {
        LyncClient _LyncClient;
        Group selectedGroup;

        public SSContacts()
        {
            InitializeComponent();
        }

        private void Window_Loaded_1(object sender, RoutedEventArgs e)
        {
            //GroupList_ListBox
            try 
            {
                _LyncClient = LyncClient.GetClient();
                LoadList();
                GroupList_ListBox.SelectedIndex = 0;
            }
            catch (LyncClientException lce) 
            {
                Debug.WriteLine(
                    "Lync client exception on GetClient() in Window Loaded " + 
                    lce.Message);
            }

        }

        /// <summary>
        /// Loads a list box with existing contact list groups
        /// by iterating on the Groups collection of the ContactManager 
        /// property on LyncClient.
        /// </summary>
        private void LoadList()
        {
            GroupList_ListBox.Items.Clear();
            foreach (Group group in _LyncClient.ContactManager.Groups)
            {
                //The Group is wrapped in a custom class to allow
                //override of ToString() method
                GroupWrapper gWrap = new GroupWrapper(group);

                GroupList_ListBox.Items.Add(gWrap);
            }
        }

        /// <summary>
        /// Loads all of the contacts for a selected group into a contact
        /// list on the UI
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GroupList_ListBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            //Get the selected group
            GroupWrapper groupToList = (GroupWrapper)GroupList_ListBox.SelectedItem;
            selectedGroup = groupToList.LyncGroup;

            //clear the contact list
            ContactList_ListBox.Items.Clear();

            foreach (Contact contact in groupToList.LyncGroup)
            {
                ContactWrapper contactWrapper = new ContactWrapper(contact);
                ContactList_ListBox.Items.Add(contactWrapper);
            }
        }

        /// <summary>
        /// remove the selected contact from every group in the users contact list
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RemoveContact_Button_Click(object sender, RoutedEventArgs e)
        {
            if (ContactList_ListBox.SelectedItem == null)
            {
                return;
            }
            ContactWrapper selectedContact = (ContactWrapper)ContactList_ListBox.SelectedItem;
            _LyncClient.ContactManager.BeginRemoveContactFromAllGroups(
                selectedContact.LyncContact,
                (ar) =>
                {
                    _LyncClient.ContactManager.EndRemoveContactFromAllGroups(ar);
                },
                null);

            //Get the currently selected group and refresh contacts
            GroupWrapper groupToList = (GroupWrapper)GroupList_ListBox.SelectedItem;
            selectedGroup = groupToList.LyncGroup;

            //refresh lync contact list for selected group
            //clear the contact list
            ContactList_ListBox.Items.Clear();

            //lets wait for a sec before refreshing
            System.Threading.Thread.Sleep(1000);

            //refresh contact list
            foreach (Contact contact in selectedGroup)
            {
                ContactWrapper contactWrapper = new ContactWrapper(contact);
                ContactList_ListBox.Items.Add(contactWrapper);
            }

        }


        private void LoadSkypeContacts_Button_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            //Lets find the folder with the skype database
            //get the users Skype Id 
            var skypeUsername = SkypeID_txt.Text;

            if (skypeUsername == "")
            {
                //prompt user to enter Skype ID
            }
            else
            {
                //lets try opening the database
                //get the roaming profile
                var skypeDatabase = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Skype\\" + skypeUsername + "\\main.db";

                //TODO: 
                //1. Check if file exists
                //2. If doesnt prompt user if Skype ID is correct
                //3. Else try opening connection
                //4. If fails let the user know the connection failed and try check the Skype ID

                SQLiteConnection m_dbConnection;
                m_dbConnection = new SQLiteConnection("Data Source=" + "'" + skypeDatabase + "'");
                m_dbConnection.Open();

                string sql = "select skypename from contacts where type=9";
                SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
                SQLiteDataReader reader = command.ExecuteReader();

                string skypeID = null;

                //Lets clear both list boxes
                SkypeContacts_ListBox.Items.Clear();
                LegacySkypeContacts_ListBox.Items.Clear();

                //lets add skype contacts with email addresses
                while (reader.Read())
                {
                    var skypeName = reader["skypename"];
                    var name = skypeName.ToString().Split(':');
                    skypeID = name[1];

                    //get namespace
                    var userName = skypeID.Split('@')[0];
                    var userNamespace = skypeID.Split('@')[1];

                    //check if namespace is valid
                    if (userNamespace == "live.com" || userNamespace == "hotmail.com" || userNamespace == "outlook.com")
                    {
                        //Add Skype Id to Lync contacts
                        //Add these to the Skype Contacts listbox
                        SkypeContacts_ListBox.Items.Add(skypeID);
                    }
                    else
                    {
                        //Create the msn id
                        string msnUserID = userName + "(" + userNamespace + ")@msn.com";
                        SkypeContacts_ListBox.Items.Add(msnUserID);
                    }
                }
                //close the sql reader
                reader.Close();

                //searchInput.SearchTextInput = skypeID;

                //var searchResult = searchInput.FindName(skypeID);
                //var state = searchInput.SearchState;
                //while (searchInput.SearchState != Microsoft.Lync.Controls.SearchState.Finished)
                //{
                //    System.Threading.Thread.Sleep(5000); // pause for 1/4 second
                //    int i = 0;
                //};




                //Get skype Ids with leagacy unernames
                string legacySkypeUsersQuery = "select skypename from contacts where type=1";
                SQLiteCommand legacySkypeUsersQueryCommand = new SQLiteCommand(legacySkypeUsersQuery, m_dbConnection);
                SQLiteDataReader legacySkypeUsersQueryReader = legacySkypeUsersQueryCommand.ExecuteReader();
                while (legacySkypeUsersQueryReader.Read())
                {
                    var legacySkypeUser = legacySkypeUsersQueryReader["skypename"];

                    //Addd to legacy Skype Contact Listbox
                    LegacySkypeContacts_ListBox.Items.Add(legacySkypeUser);
                }
            }
        }


        private void SkypeContacts_ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (SkypeContacts_ListBox.SelectedItem != null)
            {
                //Get the selected group
                string skypeContact = SkypeContacts_ListBox.SelectedItem.ToString();

                //search for skype contact
                searchInput.SearchTextInput = skypeContact;
            }
        }

        private void LegacySkypeContacts_ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }


        private void ResultList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (searchInput.SearchTextInput != "")
            {
                //lets add the users - this should be in the if else
                //we shall add it to the test group - ideally we should create a skype import group and add it there
                //Get the selected group
                GroupWrapper groupToList = (GroupWrapper)GroupList_ListBox.SelectedItem;
                selectedGroup = groupToList.LyncGroup;

                //add the selected contact to selected group in Lync
                Microsoft.Lync.Controls.SearchResult selectedContact = (Microsoft.Lync.Controls.SearchResult)ResultList.SelectedItem;
                if (selectedContact.Result.GetType().Name == "Contact")
                {
                    Contact contact = selectedContact.Result as Contact;
                    selectedGroup.BeginAddContact(contact, (ar) => { selectedGroup.EndAddContact(ar); }, null);
                }

                //refresh lync contact list for selected group
                //clear the contact list
                ContactList_ListBox.Items.Clear();

                //lets wait for a sec before refreshing
                System.Threading.Thread.Sleep(1000);

                //refresh contact list
                foreach (Contact contact in selectedGroup)
                {
                    ContactWrapper contactWrapper = new ContactWrapper(contact);
                    ContactList_ListBox.Items.Add(contactWrapper);
                }

            }

            //clear the search input text
            searchInput.SearchTextInput = "";
            
        }

    }

    internal class ContactWrapper
    {
        Contact _contact;
        private string displayName;
        internal Contact LyncContact
        {
            get
            {
                return _contact;
            }
        }
        public override string ToString()
        {
            return displayName; // 
        }
        internal ContactWrapper(Contact contact)
        {
            _contact = contact;
            displayName = _contact.GetContactInformation(ContactInformationType.DisplayName).ToString();
        }
    }

}
